import { configure, makeAutoObservable } from 'mobx';
import { getStorageSync, removeStorageSync, setStorageSync } from '@tarojs/taro';
import AuthConstant from '@/constant/AuthConstant';

configure({
  enforceActions: 'always',
});

class AuthStore {
  constructor() {
    makeAutoObservable(this, {}, {autoBind: true});
  }

  /**
   * 登录态token
   */
  token: string = getStorageSync(AuthConstant.TOKEN);

  /**
   * 标志是否处于登录
   */
  isLogin: boolean = !!this.token;

  /**
   * 当前身份
   */
  identity: string = getStorageSync(AuthConstant.IDENTITY_KEY);

  /**
   * 上一个身份
   */
  preIdentity: string = '';

  /**
   * 设置token值
   */
  setToken(token: string) {
    this.token = token;
  }

  /**
   * 设置登录态
   * @param isLogin 是否处于登录状态
   * @param totken token令牌
   */
  setLoginState(isLogin: boolean, token?: string) {
    if (!isLogin) removeStorageSync(AuthConstant.TOKEN);
    else if (isLogin && token) {
      setStorageSync(AuthConstant.TOKEN, token);
      this.token = token;
    }
    this.isLogin = isLogin;
  }

  /**
   * 设置当前身份
   */
  setIdentityState(identity: typeof AuthConstant.LANDLORD | typeof AuthConstant.TENANT) {
    setStorageSync(AuthConstant.IDENTITY_KEY, identity);
    this.identity = identity;
  }

  /**
   * 清除当前身份
   */
  clearIdentityState() {
    removeStorageSync(AuthConstant.IDENTITY_KEY);
    this.identity = '';
  }

  /**
   * 设置上一个身份
   */
  setPreIdentityState(identity: typeof AuthConstant.LANDLORD | typeof AuthConstant.TENANT) {
    this.preIdentity = identity;
  }
}

const authStore = new AuthStore();
export default authStore;